import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'
import constant from '@/common/constant/httpStatus'
import { axiosBeseUrl } from '@/common/config/baseConfig'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const instance = axios.create({
  timeout: 10000
})
instance.defaults.baseURL = axiosBeseUrl
// request拦截器
instance.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers.authorization = store.getters.token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  Promise.reject(error)
})
let lock = false
// respone 拦截器
instance.interceptors.response.use(res => {
  if (res.status === 200) {
    const data = res.data
    if (constant.NO_LOGIN === data.code && !lock) {
      if (window.location.href.slice(window.location.href.lastIndexOf('#') + 1) === '/login' || lock) return
      lock = true
      MessageBox.confirm('由于长时间未操作，请重新登录!', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        lock = false
        store.commit('user/SIGN_OUT')
        router.push({ path: '/login' })
      }).catch(e => {
        lock = false
      })
    } else if (constant.NO_LOGIN === data.code && lock) {
      return data
    } else if (constant.SUCCESS === data.code) {
      return data
    } else {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return data
    }
    // returnCode(data)
  }
}, error => {
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default instance
